//
//  BKUserPersonalInfoViewController.m
//  bestkeep
//
//  Created by windCould on 16/11/29.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserPersonalInfoViewController.h"
#import "BKMyCommon.h"
#import "SectionModel.h"
#import "BKNewUserInfoITTACell.h"
#import "BKNewUserPInfoTTCell.h"
#import "BKNewUserPInfoTTACell.h"
#import "BKUserPersonalInfoTexImgCell.h"
#import "BKUserSectionHeaderView.h"
#import "BKUserStatusInfo.h"
#import "TZImagePickerController.h"
#import "BKUserBindingViewController.h"
#import "BKUserModifyNickNameViewController.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserRetirePwdController.h"
#import "BKUserMobileConfigInfo.h"
#import "Sign.h"
#import "BKModifyUserPwdController.h"

#import "BKUserThirdLoginMannager.h"

@interface BKUserPersonalInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)NSArray * dataArr;
@property (nonatomic,strong)id userInfoModel;
@property (nonatomic,strong)UIImage * logoImg;


//三方登录
@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@property (nonatomic, strong) NSMutableArray *permissionArray;
@property (nonatomic, copy) NSString * QQName;
@property (nonatomic, copy) NSString * WiXinName;


@property (nonatomic,strong)NSDictionary * loginParDict;
@property (nonatomic,strong)NSDictionary * bindDict;



@end


@implementation BKUserPersonalInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = BKMyLocalizedString(@"BKUserMySelfInfo");
    self.view.backgroundColor = RGBCOLOR(221, 221, 221,1);
    [self verifyUserIsBindinAccount];
    self.dataArr = [self creatDataArrayWithDataModel:nil];
    [self setUpViews];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.dataArr = [self creatDataArrayWithDataModel:nil];
}

-(void)setDataArr:(NSArray *)dataArr
{
    _dataArr = dataArr;
    [self.tableView reloadData];
}

-(void)verifyUserIsBindinAccount
{
    
    [BKUserUnitRequestAPI userInfoThirdAccount:nil mycallBack:^(id obj, NSError *error) {
     
        NSDictionary *dict = obj;
        NSDictionary *paraDict = dict[@"data"];
        NSString *success = [dict[@"success"] stringValue];
        NSString *QQ = [[paraDict objectForKey:@"QQ"] stringValue];
        NSString *weiXin = [[paraDict objectForKey:@"WEIXIN"] stringValue];
        
        if ([success isEqualToString:@"1"]) {
            
            BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
            
            [userInfo.realm beginWriteTransaction];
            
            userInfo.QQbinding = QQ;
            userInfo.wechatBindin = weiXin;
            
            [userInfo.realm commitWriteTransaction];
            
            self.dataArr = [self creatDataArrayWithDataModel:nil];
            
        } else {
        
            NSLog(@"验证绑定网络请求失败");
            NSLog(@"%@",dict[@"msg"]);
        }
    }];

}

//解绑
-(void)removeBindinWithType:(NSString *)type
{
    NSDictionary * dataDict = @{@"type":type};
    
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI userInfoRemoveThirdAccount:dataDict mycallBack:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        NSDictionary *Dict = obj;
        NSDictionary *dataDict = Dict[@"data"];
        NSString *msg = dataDict[@"msg"];
        
        if ([dataDict[@"success"] boolValue]) {
            
            if ([type isEqualToString:@"1"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
               
                [userInfo.realm beginWriteTransaction];
                
                userInfo.QQbinding = @"0";
                
                [userInfo.realm commitWriteTransaction];
               self.dataArr = [self creatDataArrayWithDataModel:nil];
            }
            
            if ([type isEqualToString:@"2"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                
                [userInfo.realm beginWriteTransaction];
                
                userInfo.wechatBindin = @"0";
                
                [userInfo.realm commitWriteTransaction];
                self.dataArr = [self creatDataArrayWithDataModel:nil];
            }
            [HUD showSuccessMessage:msg];
            
        } else {
           
            [HUD showErrorMessage:msg];
            
        }
    }];

}

//重新绑定
-(void)reBindinAccountWithDict:(NSDictionary *)dict
{
    [BKIndicationView dismiss];
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI userInfoBindAccount:dict mycallBack:^(id obj, NSError *error) {
         [BKIndicationView dismiss];
        NSDictionary *dictData = obj;
        NSDictionary *data = dictData[@"data"];
        NSString *msg = data[@"msg"];
        if ([data[@"success"] boolValue]) {
            
            if ([dict[@"openType"] isEqualToString:@"1"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                
                [userInfo.realm beginWriteTransaction];
                
                userInfo.QQbinding = @"1";
                
                [userInfo.realm commitWriteTransaction];
                
                self.dataArr = [self creatDataArrayWithDataModel:nil];
            }
            
            if ([dict[@"openType"] isEqualToString:@"2"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                
                [userInfo.realm beginWriteTransaction];
                
                userInfo.wechatBindin = @"1";
                
                [userInfo.realm commitWriteTransaction];
                
                self.dataArr = [self creatDataArrayWithDataModel:nil];
            }
            
            [HUD showSuccessMessage:msg];
        } else {
        
            [HUD showErrorMessage:msg];
        
        }
        
    }];

}


#pragma mark ============= NetRequest ====================================

-(void)upLoadImgeWithImgDataStr:(NSString*)imgDataStr
{
    [BKIndicationView dismiss];
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI upLoadUserHeadImgeDataStr:imgDataStr resultBlock:^(id obj, NSError *error) {
        
       [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                
                [userInfo.realm beginWriteTransaction];
                
                userInfo.photo = result.data;
                
                [userInfo.realm commitWriteTransaction];
                
                self.dataArr = [self creatDataArrayWithDataModel:nil];
                [HUD showSuccessMessage:result.msg];
            } else {
            
             [HUD showErrorMessage:result.msg];
            }
        } else {
        
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
            NSLog(@"网络请求失败");
        
        }
    }];
    
}

#pragma mark ============= Cell的点击事件 =================================

-(void)goToChooseNewLogo
{
    [self addImgFromPictureLibrary];
}

-(void)goToModifyNickName
{
    BKUserModifyNickNameViewController * modifyNick = [[BKUserModifyNickNameViewController alloc]init];
    [self.navigationController pushViewController:modifyNick animated:YES];
}

-(void)bingdinWechatAccount
{

    if (![WXApi isWXAppInstalled]) {
        
        [HUD showErrorMessage:@"您还未安装微信客户端"];
        return;
    }
    
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    if ([userInfo.wechatBindin isEqualToString:@"1"]) {
        
        if (IOS8) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您是否解除微信绑定" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *relieveAction = [UIAlertAction actionWithTitle:@"解除绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self removeBindinWithType:@"2"];
            }];
            [alert addAction:cancleAction];
            [alert addAction:relieveAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您是否解除微信绑定" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"解除绑定", nil];
            alertView.tag = 1002;
            [alertView show];
        }
        
        
    } else{
        
        [BKUserThirdLoginMannager getUserInfoForPlatform:@"wechat" result:^(UMSocialUserInfoResponse * obj, NSError *error) {
            
            if (!error) {
                
                NSString * openType = @"2";
                
                NSDictionary * weiXinBindDict = @{@"openId":obj.openid,
                                                 @"openType":openType,
                                                 @"accessToken":obj.accessToken
                                                 };
                
                [self reBindinAccountWithDict:weiXinBindDict];
            } else {
                
                NSLog(@"%@",error.localizedDescription);
                
            }
        }];
    
    }
}

-(void)bingdinQQAccount
{
    if (![TencentOAuth  iphoneQQInstalled]) {
        
        [HUD showErrorMessage:@"您还未安装QQ客户端"];
        return;
    }
    
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    if ([userInfo.QQbinding isEqualToString:@"1"]) {
        
        if (IOS8) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您是否解除QQ绑定" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *relieveAction = [UIAlertAction actionWithTitle:@"解除绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self removeBindinWithType:@"1"];
            }];
            [alert addAction:cancleAction];
            [alert addAction:relieveAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
        
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您是否解除QQ绑定" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"解除绑定", nil];
            alertView.tag = 1001;
            [alertView show];
        }
        
        
    } else{
        
        [BKUserThirdLoginMannager getUserInfoForPlatform:@"QQ" result:^(UMSocialUserInfoResponse * obj, NSError *error) {
            
            if (!error) {
            
                NSString * openType = @"1";
                NSDictionary * bindDict = @{@"openId":obj.openid,
                                           @"openType":openType,
                                           @"accessToken":obj.accessToken
                                           };
                [self reBindinAccountWithDict:bindDict];
                
            } else {
                
                NSLog(@"%@",error.localizedDescription);
            }
            
        }];
    }
    
}

#pragma mark- alertView代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001) {
        
        if (buttonIndex == 0) {
            
            return;
        }
        else
        {
            [self removeBindinWithType:@"1"];
        }
    }
    
    if (alertView.tag == 1002) {
        
        if (buttonIndex == 0) {
            
            return;
        }
        else
        {
            [self removeBindinWithType:@"2"];
        }
        
    }
    
}

-(void)modifyLoginPwd
{
    BKModifyUserPwdController * retireVc = [[BKModifyUserPwdController alloc]init];
    [self.navigationController pushViewController:retireVc animated:YES];
}


#pragma mark ============= mainTableViewDelegate =======================

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SectionModel * sect = self.dataArr[section];
    NSInteger count = sect.cells.count;
    return count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel * sect = self.dataArr[indexPath.section];
    CellModel * cellModel = sect.cells[indexPath.row];
    return cellModel.height;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SectionModel * sect = self.dataArr[indexPath.section];
    CellModel * cellModel = sect.cells[indexPath.row];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellModel.reuseIdentifier];
    if (!cell) {
        
        cell = [[NSClassFromString(cellModel.className) alloc]initWithStyle:cellModel.style reuseIdentifier:cellModel.reuseIdentifier ];
    }
    cell.separatorInset = UIEdgeInsetsMake(0, -20, 0, 0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SectionModel * sect = self.dataArr[section];
    
    BKUserSectionHeaderView * headerView = [[BKUserSectionHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 30)];
    headerView.titleLabel.textColor = HexColor(0x888888);
    
    headerView.titleLabel.font = [UIFont systemFontOfSize:12];
    headerView.titleStr = sect.title;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    SectionModel * sect = self.dataArr[section];
    return  sect.headerhHeight;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return FLT_MIN;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel * sect = self.dataArr[indexPath.section];
    CellModel * cellModel = sect.cells[indexPath.row];
        if ([cell respondsToSelector:@selector(fillData:)]) {
            
            [cell performSelector:@selector(fillData:) withObject:cellModel];
        }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel * sect = self.dataArr[indexPath.section];
    CellModel * cellModel = sect.cells[indexPath.row];
    
    NSString * selString = cellModel.selectorString;
    if (selString) {
         SEL selec = NSSelectorFromString(selString);
        if ([self respondsToSelector:selec]) {
            
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
            
            [self performSelector:selec withObject:nil];
        }
    }
}


#pragma mark =========================布局==========================================

-(void)setUpViews
{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.backgroundColor = ThemeBackgroundColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self.tableView reloadData];
}

-(NSArray<SectionModel *> *)creatDataArrayWithDataModel:(id)model
{
    
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];

    CellModel * headImgVModel = [CellModel cellModelWithTitle:@"头像" subTitle:nil image:userInfo.photo sel:@"goToChooseNewLogo"];
    headImgVModel.className = @"BKUserPersonalInfoTexImgCell";
    headImgVModel.userInfo = model;
    headImgVModel.reuseIdentifier = BKUserInfoTextHeadViewCell;
    headImgVModel.height = 45;

    CellModel * nickModel = [CellModel cellModelWithTitle:@"昵称" subTitle: userInfo.nickName image:nil sel:@"goToModifyNickName"];
    nickModel.className = @"BKNewUserPInfoTTACell";
    nickModel.userInfo  = model;
    nickModel.reuseIdentifier = BKNewUserInfoITTACellId;
    nickModel.height = 45;
   
    CellModel * emailAddress = [CellModel cellModelWithTitle:@"个人邮箱" subTitle: userInfo.email image:nil sel:@"goToPersonalEmail"];
    emailAddress.className = @"BKNewUserPInfoTTCell";
    emailAddress.userInfo = model;
    emailAddress.reuseIdentifier = BKNewUserPInfoTTCellId;
    emailAddress.height = 45;
    
    CellModel * workZone = [CellModel cellModelWithTitle:@"所属行业" subTitle:userInfo.job image:nil sel:@"goToWorkZone"];
    workZone.className = @"BKNewUserPInfoTTCell";
    workZone.userInfo = model;
    workZone.reuseIdentifier = BKNewUserPInfoTTCellId;
    workZone.height = 45;
    
    SectionModel * sect1 = [SectionModel sectionModelWithTitle:@"个人资料" cells:@[headImgVModel,nickModel,emailAddress,workZone]];
    sect1.headerhHeight = 30;
  
    CellModel * account = [CellModel cellModelWithTitle:@"登录账号" subTitle:  userInfo.userName image:nil sel:@"loginAccount"];
    account.className = @"BKNewUserPInfoTTCell";
    account.userInfo = model;
    account.reuseIdentifier = BKNewUserPInfoTTCellId;
    account.height = 45;
    
    NSString * QQStatus;
    if ([userInfo.QQbinding isEqualToString:@"1"]) {
        
        QQStatus = @"已绑定";
    } else {
    
        QQStatus = @"去绑定";
    }
    
    NSString * wechatStatus ;
    if ([userInfo.wechatBindin isEqualToString:@"1"]) {
        
        wechatStatus = @"已绑定";
    } else {
    
        wechatStatus = @"去绑定";
    }

    CellModel * wechatLogin = [CellModel cellModelWithTitle:@"微信账号" subTitle:wechatStatus image:@"BK_My_Wlogo_" sel:@"bingdinWechatAccount"];
    wechatLogin.className = @"BKNewUserInfoITTACell";
    wechatLogin.userInfo = model;
    wechatLogin.reuseIdentifier = BKNewUserInfoITTACellId;
    wechatLogin.height = 45;
    
    CellModel * qqLogin = [CellModel cellModelWithTitle:@"QQ账号" subTitle:QQStatus image:@"BK_My_logo_" sel:@"bingdinQQAccount"];
    qqLogin.className = @"BKNewUserInfoITTACell";
    qqLogin.userInfo = model;
    qqLogin.reuseIdentifier = BKNewUserInfoITTACellId;
    qqLogin.height = 45;
    
    CellModel * modifyPwd = [CellModel cellModelWithTitle:@"修改密码" subTitle:nil image:nil sel:@"modifyLoginPwd"];
    modifyPwd.className = @"BKNewUserPInfoTTACell";
    modifyPwd.userInfo = model;
    modifyPwd.reuseIdentifier = BKNewUserPInfoTTACellId;
    modifyPwd.height = 45;
    
    SectionModel * sect2 = [SectionModel sectionModelWithTitle:@"账号与安全" cells:@[account,wechatLogin,qqLogin,modifyPwd]];
    sect2.headerhHeight = 30;
    NSArray * dataArr = @[sect1,sect2];
    
    return dataArr;
}

#pragma mark =========================选择图像===================================

//添加图片
-(void)addImgFromPictureLibrary
{
    if (iOSSyStem >= 8.0) {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self takePhotoSelectImgWithSourceType:UIImagePickerControllerSourceTypeCamera];
            }];
            
            [alert addAction:action1];
        }
        
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self selectImgFromPhotoLibraryMaxImagesCount:1];
        }];
        
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action2];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

          
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选取", nil];
            [sheet showInView:self.view];
            
        } else {
            
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取", nil];
            [sheet showInView:self.view];
        }
        
    }
}

-(void)takePhotoSelectImgWithSourceType:(UIImagePickerControllerSourceType)surceType
{
    UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerController.sourceType = surceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *icon = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(icon,nil,nil,nil);
    [self dealWithImg:icon];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)selectImgFromPhotoLibraryMaxImagesCount:(NSInteger)maxImgesCount
{
    TZImagePickerController *imgPickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxImgesCount delegate:self];
    [imgPickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL result) {
        
        for (UIImage *image in photos)
        {
            [self dealWithImg:image];
        }
    }];
    [self presentViewController:imgPickerVc animated:YES completion:nil];
    
}

- (void)dealWithImg:(UIImage *)image{
    
    CGSize imageSize = image.size;
    imageSize.width = image.size.width / 2;
    imageSize.height = image.size.height / 2;
    CGFloat compressionQuality;
    
    if(image.size.height > 3000 || image.size.width > 3000) {
        compressionQuality = 0.3;
    } else if (image.size.height > 1500 || image.size.width > 1500){
        compressionQuality = 0.5;
    } else {
        compressionQuality = 0.8;
    }
    
    UIImage * img = [self imageWithImage:image scaledToSize:imageSize];
    NSData *data = UIImageJPEGRepresentation(img, compressionQuality);
    NSString *encodeStr  = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [self upLoadImgeWithImgDataStr:encodeStr];
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

@end
